const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [
    `${[year, month, day].map(formatNumber).join('/')}`,
    `${[hour, minute, second].map(formatNumber).join(':')}`
  ]
  
  
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}


const getDateDiff =  (dateTimeStamp) => {
  if(!dateTimeStamp){
    return '刚刚'
  }
  dateTimeStamp = new Date(dateTimeStamp).getTime()
  var result = ''
  var minute = 1000 * 60
  var hour = minute * 60
  var day = hour * 24
  var month = day * 30
  var now = new Date().getTime()
  var diffValue = now - dateTimeStamp
  if (diffValue < 0) return
  var monthC = diffValue / month
  var weekC = diffValue / (7 * day)
  var dayC = diffValue / day
  var hourC = diffValue / hour
  var minC = diffValue / minute
  if (monthC >= 1) {
    result = "" + parseInt(monthC) + "月前"
  }
  else if (weekC>=1) {
    result = "" + parseInt(weekC) + "周前"
  }
  else if (dayC >= 1) {
    result = ""+ parseInt(dayC) + "天前"
  }
  else if (hourC >= 1){
    result = "" + parseInt(hourC) + "小时前"
  }
  else if (minC >= 1) {
    result = ""+ parseInt(minC) + "分钟前"
  } else {
    result = "刚刚"
  }
  return result
}


// 考试状态解析 ks_date 考试日期 ks_time_end 考试结束时间 auth_day 考前多少天开考
const getTestStuts = (ks_date = null, auth_day = null, ks_time_end = null) => {
  
  let status = 1 // 1代开始 2进行中 3已结束
  let status_name = '待开始'
  if(ks_date && auth_day) {
    if(ks_time_end){
      // 如果存在结束时间
      ks_date = `${ks_date} ${ks_time_end}:00`
    }
    let time = new Date().getTime() // 现在时间
    let ksTime = new Date(ks_date.replace(/-/g,'/')).getTime() // 结束上传时间 毫秒
    let ksTimeStart = ksTime - (auth_day*24*60*60*1000) // 开始上传时间 毫秒
    if(time > ksTime){
      status = 3 // 已结束
      status_name = '已结束' // 已结束
    } else if(time > ksTimeStart && time < ksTime){
      status = 2 // 进行中
      status_name = '进行中' // 已结束
    } else if(time <= ksTimeStart){
      status = 1 // 待开始
      status_name = '待开始' // 已结束
    }
  } else {
    status = 2 // 进行中
    status_name = '进行中' // 已结束
  }

  return {
    status,
    status_name
  }
}


module.exports = {
  formatTime,
  getDateDiff,
  getTestStuts
}
